'use strict';

const axios = require("axios");
const { log } = require("npmlog");
const semver = require("semver")
const urljoin = require("url-join")

module.exports = {
  getNpmInfo,
  getNpmVersion,
  getNpmSemverVersion,
  getNpmLatestVersion,
  getDefaultRegistry
};

function getNpmInfo(npmName, registry) {
  if (!npmName) {
    return null
  }
  // 获取 npm 源
  const registryUrl = registry || getDefaultRegistry()
  const npmInfoUrl = urljoin(registryUrl, npmName)
  return axios.get(npmInfoUrl).then(res => {
    if (res.status == 200) {
      return res.data
    }
  })
}

function getDefaultRegistry(isOriginal = false) {
  return isOriginal ? "https://registry.npmjs.org" : "https://registry.npm.taobao.org"
}

// 处理所有版本号
async function getNpmVersion(npmName, registry) {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return data.versions && Object.keys(data.versions);
  } else {
    return [];
  }
}

// 比对当前版本之上的 所有版本号
function getSemverVersion(besVersion, version) {
  version = version && version.filter(version =>
    // 获取当前版本 之后所有的版本 
    // 兼容手动排序
    semver, semver.satisfies(version, `>{besVersion}`)
  ).sort((a, b) => semver.gt(b, a) ? 1 : -1)
  return version
}

async function getNpmSemverVersion(besVersion, npmName, registry) {
  const version = await getNpmVersion(npmName, registry)
  const newVersion = getSemverVersion(besVersion, version)
  // 获取所有的 版本号数组 
  // console.log(newVersion);

  // 返回最新版本号
  if (newVersion && newVersion.length > 0) {
    return newVersion[0]
  }
  return null
}


// 根据传入latest 转成最新的版本号

async function getNpmLatestVersion(npmName, registry) {
  let versions = await getNpmVersion(npmName, registry)
  console.log(npmName);
  // if (versions) {
  //   return versions.sort((a, b) => semver.gt(b, a)[0])
  // }
  // return null
}